/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package migracion;

import entidades.CicloNewlong;
import entidades.EtapaNewlong;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import util.MySQL;

/**
 *
 * @author scamisay
 */
public class ArregloPorLoDeSeba {
    public static void main(String [] args) throws SQLException{
        Integer limit = EtapaNewlong.listar().size();
        Integer i = 0;
        for(EtapaNewlong en : EtapaNewlong.listar()){
            en.setOcupado(sum(en));
            en.guardar();
            i++;
            if(i%50==0){
                System.out.println(i+"/"+limit);
            }
        }
    }
    
    public static void recalcularEtapasPorNewlong(Integer newlong) throws SQLException{
        List<EtapaNewlong> etapas = EtapaNewlong.listar();

        /*Me quedo con las etapas que pertenecen a esta newlong*/
        Iterator<EtapaNewlong> it = etapas.iterator();
        while(it.hasNext()){
            EtapaNewlong e = it.next();
            if( CicloNewlong.getCicloNewlongById(e.getCicloId()).getNewlongId()!=newlong){
                it.remove();
            }
        }
        
        recalcularEtapasNewlong(etapas);
    }
    
    public static void recalcularEtapasPorCiclos(int cicloId) throws SQLException{
        List<EtapaNewlong> etapas = EtapaNewlong.listar(cicloId);
        recalcularEtapasNewlong(etapas);
    }
    
    private static void recalcularEtapasNewlong(List<EtapaNewlong> etapas) throws SQLException{
        for(EtapaNewlong en : etapas){
            en.setOcupado(sum(en));
            en.guardar();
        }
    }
    
    public static Integer sum(EtapaNewlong en) throws SQLException{
        Integer suma = 0;
        ResultSet result = MySQL.executeQuery(
                "select sum(ot.cantidad) as suma "+
                "from ordenes_trabajo ot, ciclos_newlong cn, etapas_newlong en "+
                "where en.ciclo_id = cn.id and "+
                "cn.id = ot.ciclo_newlong_id and "+
                "ot.formato_id = en.formato_id "+
                "and en.id = "+en.getId()+
                " group by en.id;"
                );
		if(result.next()) {
                    suma = result.getInt("suma");
                }
		result.getStatement().close();
	return suma;
    }
}
